<template>
  <div class="map-blk">
    <div class="iot-firm">
      <!-- <i class="iconfont icon-search"></i> -->
      <!-- <el-select
				v-model="firmId"
				filterable
				remote
				placeholder="请输入企业名称"
				:remote-method="remoteMethod"
				:loading="loading"
				@change="changeFirm">
				
				<el-option
					v-for="item in firmList"
					:key="item.id"
					:label="item.name"
					:value="item.id">
				</el-option>
			</el-select> -->
      <!-- <el-select
				v-model="firmId"
				filterable
				placeholder="请输入企业名称"
				@change="changeFirm">
				
				<el-option
					v-for="item in firmList"
					:key="item.id"
					:label="item.name"
					:value="item.id">
				</el-option>
			</el-select> -->
    </div>
    <div class="switch-map">
      <el-dropdown>
        <p class="el-dropdown-link map-type-drop-link">
          <span>{{ mapTypeMap[mapType] }}</span>
          <i class="el-icon-arrow-down el-icon--right"></i>
        </p>
        <el-dropdown-menu slot="dropdown" class="map-type-dropdown-menu">
          <el-dropdown-item>
            <p
              :class="{ active: mapType == 'amap' }"
              @click="switchMap('amap')"
            >
              地图
            </p>
          </el-dropdown-item>
          <el-dropdown-item>
            <p
              :class="{ active: mapType == 'bigmap' }"
              @click="switchMap('bigmap')"
            >
              混合
            </p>
          </el-dropdown-item>
          <el-dropdown-item>
            <p
              :class="{ active: mapType == 'bgImg' }"
              @click="switchMap('bgImg')"
            >
              背景图片
            </p>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- <p :class="{ active: mapType == 'amap' }" @click="switchMap('amap')">地图</p>
            <p :class="{ active: mapType == 'bigmap' }" @click="switchMap('bigmap')">混合</p> -->
    </div>
    <div id="map" class="map" v-show="mapType == 'amap'"></div>
    <div id="bigmap" class="map" v-show="mapType == 'bigmap'"></div>
    <!-- <div
      class="map-bg"
      v-show="mapType == 'bgImg'"
      :style="{ backgroundImage: 'url(' + bgPath + ')' }"
    ></div> -->
    <div
      class="map-bg"
      v-if="mapType == 'bgImg' && bgImgMarker.file"
      @mousewheel="handleScroll"
    >
      <floorMarker
        :style="{ transform: `scale(${ImgScale})` }"
        v-drag
        :img="bgImgMarker.file"
        :coordList="bgImgMarker.coordinateData"
      ></floorMarker>
    </div>
    <!-- <div id="map" class="map"></div> -->
    <!-- 企业详情 start -->
    <el-dialog
      v-if="firmModalVisible"
      :title="firmTitle"
      :visible.sync="firmModalVisible"
      :width="870 * scale + 'px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @open="openFirmDetail"
    >
      <FirmDetail ref="firmDetail" :id="firmId"> </FirmDetail>
    </el-dialog>
    <!-- 企业详情 end -->
    <!-- 处置 start -->
    <!-- <el-dialog
            title="报警处置"
            v-if="handleModalVisibleSingle"
            :visible.sync="handleModalVisibleSingle"
            :width="handleModalWidth * scale + 'px'"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            destroy-on-close
            @open="openHandleModal(activeAlarm)"
            @close="closeHandleAlarm(activeAlarm, 'modalClose')"
        >
            <div class="flex">
                <div :style="{ width: 450 * scale + 'px', marginRight: 30 * scale + 'px' }">
                    <Handle
                        :ref="'handle' + (activeAlarm && activeAlarm.id)"
                        :isAutoClose="true"
                        :scale="scale"
                        :activeData="activeAlarm"
                        :activeDevice="alarmDevices[0]"
                        @success="handleSuccessAction(activeAlarm)"
                        @fail="handling = false"
                        @submitting="handling = true"
                        @cancel="closeHandleAlarm(activeAlarm, 'cancel')"
                        @autoClose="closeHandleAlarm(activeAlarm, 'autoClose')"
                    >
                    </Handle>
                </div>
                <div class="flex-1">
                    <SmokeAlarmModal
                        v-if="hasAlarmMedia"
                        :planeGraphDetail="planeGraphDetail"
                        :monitorList="smokeDeviceMonitorList"
                        ref="smokeAlarmModal"
                    ></SmokeAlarmModal>
                </div>
            </div>

            <div
                slot="footer"
                :style="{ paddingRight: handleModalWidth > 1000 ? 1000 * scale + 'px' : '0' }"
            >
                <el-button
                    type="cancel"
                    @click="showMonitor"
                    v-if="alarmDevices[0] && alarmDevices[0].productId == 6002"
                    >鹰眼e通</el-button
                >
                <el-button type="cancel" @click="cancelHandle(activeAlarm)">取消</el-button>
                <el-button
                    type="primary"
                    :loading="handling"
                    @click="submitHandleAction(activeAlarm)"
                    :disabled="!$store.getters.hasEditPermission"
                    >处置</el-button
                >
            </div>
        </el-dialog> -->
    <AlarmHandle
      v-if="handleModalVisibleSingle"
      :visible.sync="handleModalVisibleSingle"
      :activeAlarm="activeAlarm"
      :activeDevice="alarmDevices[0]"
      :autoClose="true"
      @success="handleSuccessAction(activeAlarm)"
      @showMonitor="showMonitor"
    ></AlarmHandle>
    <!-- <el-dialog v-if="handleModalVisible" title="报警处置" :visible.sync="handleModalVisible" :width="500*scale + 'px'" :close-on-click-modal="false" :close-on-press-escape="false" destroy-on-close>
			<Handle 
				ref="handle"
				:scale="scale"
	    		:activeData="activeAlarm"
				:alarmDevice="alarmDevice"
	    		@success="handleSuccessAction"
	    		@fail="handling=false"
	    		@submitting="handling=true"
	    		@cancel="handleModalVisible=false"
	    	>
	    	</Handle>
	    	<div slot="footer">
	    		<el-button type="cancel" @click="closeDoor" v-if="alarmDevice && alarmDevice.productId==6002">远程关门</el-button>
	    		<el-button type="cancel" @click="showMonitor" v-if="alarmDevice && alarmDevice.productId==6002">鹰眼e通</el-button>
	    		<el-button type="cancel" @click="cancelHandle">取消</el-button>
		  		<el-button type="primary" :loading="handling" @click="submitHandleAction" :disabled="!$store.getters.hasEditPermission">处置</el-button>
		  	</div>
		</el-dialog> -->
    <!-- 处置 end -->
    <!-- 设备详情 start -->
    <el-dialog
      v-if="detailModalVisible"
      title="设备详情"
      :visible.sync="detailModalVisible"
      :width="1000 * scale + 'px'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <DeviceDetail
        ref="detail"
        :rfid="alarmDevice.rfid"
        :id="alarmDevice.id"
        :productId="alarmDevice.productId"
        :classify="alarmDevice.deviceClassify"
        :number="alarmDevice.number"
        :scale="scale"
        @cancel="detailModalVisible = false"
      >
      </DeviceDetail>
    </el-dialog>
    <!-- 设备详情 end -->
    <!-- 平面图 start -->
    <div class="floor-marker-modal" v-if="planeGraphVisible">
      <h4 class="mb-10">平面图</h4>
      <floorMarker
        :img="planeGraphDetail.path"
        :coordList="planeGraphDetail.coordinateData"
      ></floorMarker>
      <div class="text-center">
        <el-button type="default" @click="planeGraphVisible = false"
          >关闭</el-button
        >
      </div>
    </div>
    <!-- 平面图 end -->

    <!-- 烟感设备报警摄像头、平面图 -->
    <!-- <SmokeAlarmModal
            v-if="smokeAlarmVisible"
            :visible.sync="smokeAlarmVisible"
            :planeGraphDetail="planeGraphDetail"
            :monitorList="smokeDeviceMonitorList"
            ref="smokeAlarmModal"
        ></SmokeAlarmModal> -->
    <!-- 详情 start -->
    <el-dialog
      v-if="unitModalVisible"
      :modal="false"
      :title="unitModalTitle"
      :visible.sync="unitModalVisible"
      width="1000px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <Detail
        ref="detail"
        :data="activeData"
        @success="submitSuccessAction"
        @cancel="unitModalVisible = false"
      >
      </Detail>
    </el-dialog>
    <!-- 详情 end -->
  </div>
</template>
<script>
import { mapState } from "vuex";
import AMap from "AMap";
import FirmDetail from "@/components/iot/FirmDetail.vue";
import Handle from "@/components/HandleAlarm.vue";
import DeviceDetail from "@/components/device/DeviceDetail.vue";
import floorMarker from "@/components/archive/FloorMarker";
import SmokeAlarmModal from "@/components/iot/SmokeAlarmModal";
import AlarmHandle from "@/components/iot/AlarmHandle";
import Detail from "@/components/census/record/RecordDetail.vue";

let indoorMap;
let map;
let cluster;
let bigmap;
let markers = [];
let clusterMarkers = {};
let alarmMarker = {};
let socket = null;
let alarmAudio = require("@/assets/audio/620.wav");
let alarmTimer = null;
let clearTimer = null;
export default {
  name: "Map",
  components: {
    FirmDetail,
    Handle,
    DeviceDetail,
    floorMarker,
    SmokeAlarmModal,
    AlarmHandle,
    Detail,
  },
  props: {
    dataList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      type: this.$route.query.type || "fireControl",
      textLayer: null,
      dataSet: null,
      animationLayer: null,
      loading: false,
      firmList: [],
      firmId: "",
      firmTitle: "",
      firmModalVisible: false,
      handleModalVisible: {},
      handleModalVisibleSingle: false,
      hasAlarmMedia: false,
      handling: false,
      // activeAlarm: null,
      activeMarkerId: "",
      audio: null,
      isSoundPlaying: false,
      alarmDevice: null,
      detailModalVisible: false,
      mapType: "amap",
      activeAlarms: [],
      alarmDevices: [],
      planeGraphVisible: false,
      planeGraphDetail: null,
      smokeAlarmVisible: false,
      smokeDeviceMonitorList: [],
      companyInfo: {},
      mapTypeMap: {
        amap: "地图",
        bigmap: "混合",
        bgImg: "背景图片",
      },
      bgPath: "",
      bgImgMarker: {},
      alarmData: [],
      ImgScale: 1.0,
      unitModalVisible: false,
      activeData: {},
    };
  },
  watch: {
    dataList(newVal) {
      // console.log('map data change')
      // this.createMarkers()
    },
  },
  computed: {
    ...mapState(["scale", "siteInfos"]),
    isAdmin() {
      return this.siteInfos && this.siteInfos.userType == 1;
    },
    handleModalWidth() {
      return this.hasAlarmMedia ? 1500 : 500;
    },
    deviceClassify() {
      let typeId =
        this.config.typeMap[this.type] == 100
          ? ""
          : this.config.typeMap[this.type];
      return typeId || "0";
    },
    activeAlarm() {
      if (this.activeAlarms.length > 0) {
        return this.activeAlarms[0];
      }
      return null;
    },
  },
  // 自定义指令
  directives: {
    drag: {
      // 指令的定义
      bind: function (el) {
        var odiv = el; // 获取当前元素
        var dragFlag = false;
        el.style.position = "absolute"; // 这一步一定不要忘记
        var x, y;
        odiv.style.cursor = "move";
        odiv.onmousedown = (e) => {
          e = e || window.event;
          x = e.clientX - odiv.offsetLeft;
          y = e.clientY - odiv.offsetTop;
          dragFlag = true;
          document.onmousemove = (e) => {
            if (dragFlag) {
              e = e || window.event;
              odiv.style.left = e.clientX - x + "px";
              odiv.style.top = e.clientY - y + "px";
            }
          };
          document.onmouseup = (e) => {
            document.onmousemove = null;
            document.onmouseup = null;
            dragFlag = false;
          };
        };
      },
    },
  },
  created() {
    if (this.type !== "command") {
      this.openSocket();
      this.getScreenSetting();
      this.getFirmList();
    }
  },
  mounted() {
    //监听鼠标滚动事件
    if (this.siteInfos.userType == 2) {
      this.getCompanyInfo();
    } else {
      this.initMap();
    }
    // this.playSound()
    // setTimeout(()=>{
    // 	this.playSound()
    // },2000)
    // setTimeout(()=>{
    // 	this.playSound()
    // },4000)
    // setTimeout(()=>{
    // 	this.playSound()
    // },6000)
    // setTimeout(()=>{
    // 	this.playSound()
    // },8000)
    // setTimeout(()=>{
    // 	this.showAlarmInMap({number:123 ,lon:119.122356,lat:36.713929,notificationType:1})
    // },2000)
    // setTimeout(() => {
    //     this.showAlarmInMap({
    //         number: 863318067877102,
    //         lon: 119.124367,
    //         lat: 33.544985,
    //         deviceClassify: 3,
    //         notificationType: 1,
    //         alarmId: "79110ba3-eaf4-48eb-9bb6-7bda8242990c",
    //     })
    // }, 2000)
    // number=123456987,lon=119.152108,lat=36.711705,dataType=1,deviceClassify=3,notificationType=1,alarmId=b36c2884-97d1-43c8-878a-5090a2e9d3b2
  },
  methods: {
    handleScroll(e) {
      if (e.deltaY > 0) {
        this.ImgScale -= 0.1;
      } else {
        this.ImgScale += 0.1;
      }
    },
    getAlarmData(state) {
      let params = {
        page: 1,
        limit: 1000,
        isChildren: 2,
        currentstate: state,
      };
      this.$get("/fireFightingIOT/device/deviceListPage", params).then(
        (res) => {
          this.bgImgMarker.coordinateData.forEach((item) => {
            if (res.data.totalSize !== 0) {
              res.data.Items.forEach((sitem) => {
                if (item.deviceId == sitem.number && state == 2) {
                  this.$set(item, "isWarn", true);
                } else if (item.deviceId == sitem.number && state == 3) {
                  this.$set(item, "isWarn", "offline");
                }
              });
            } else if (
              (item.isWarn == true && state == 2) ||
              (item.isWarn == "offline" && state == 3)
            ) {
              this.$set(item, "isWarn", false);
            }
          });
        },
        (err) => {}
      );
    },
    getScreenSetting() {
      this.$get("/systemsetup/systemsetup/largeScreenList").then(
        (res) => {
          this.loading = false;
          const audio = res.data.find((item) => item.type == 2);
          if (audio) {
            alarmAudio = audio.file;
          }
          const bg = res.data.find((item) => item.type == 1);
          if (bg) {
            // this.bgPath = bg.file;
            this.bgImgMarker = bg;
            const mapTypeIdMap = {
              1: "amap",
              2: "bgImg",
              3: "bigmap",
            };
            this.$store.commit("setMapType", mapTypeIdMap[bg.defaultOption]);
            this.mapType = this.$store.state.mapType;
            // 监管账号只展示单位不展示设备报警
            if (this.mapType == "bgImg" && !this.isAdmin) {
              this.getAlarmData(2);
              this.getAlarmData(3);
              clearTimer = setInterval(() => {
                this.getAlarmData(2);
                this.getAlarmData(3);
              }, 15000);
            }
          } else {
            this.$store.commit("setMapType", "amap");
          }
        },
        (err) => {
          this.loading = false;
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getCompanyInfo() {
      this.$get("/business/business/detail", {
        id: this.siteInfos.homeId,
      }).then((res) => {
        this.companyInfo = res.data;
        this.initMap();
      });
    },
    openHandleModal(item) {
      // console.log('openHandleModal',item)
    },
    switchMap(type) {
      if (this.mapType == type) return;
      this.mapType = type;
      // this.$store.commit("setMapType", this.mapType);
      this.$nextTick(() => {
        if (type == "amap") {
          if (!map) {
            this.initMap();
          }
        } else if (type == "bigmap") {
          if (!bigmap) {
            this.initBigMap();
          }
        } else {
          this.getScreenSetting();
        }
      });
    },
    closeDoor() {
      this.$refs.handle.closeDoor();
    },
    onDoorClosed() {
      //
    },
    // 播放险情警报音频
    playSound() {
      if (this.$route.path != "/IOT") return;
      if (!this.audio) {
        this.audio = document.createElement("audio");
        //是否进行预加载
        this.audio.preload = "auto";
        this.audio.autoplay = false;
        //是否显示隐藏按钮
        this.audio.controls = true;
        this.audio.hidden = true;
        //绑定音乐结束事件，当音乐播放完成后，将会触发playEndedHandler方法
        this.audio.addEventListener("ended", this.playEndedHandler, false);
        this.audio.addEventListener(
          "error",
          () => {
            this.audio.play();
          },
          false
        );
        this.audio.addEventListener(
          "canplay",
          () => {
            this.audio.play();
            // console.log('正在播放->'+this.audio.src)
          },
          false
        );
        document.body.appendChild(this.audio);
      }

      // if(this.soundList.length==0) return
      // var soundItem = this.soundList[0]
      this.audio.src = alarmAudio;
      this.isSoundPlaying = true;
    },
    // 监听每个音频播放完毕
    playEndedHandler() {
      // console.log('playEndedHandler')
      this.isSoundPlaying = false;
    },
    getAlarmDetail(id, cbk) {
      this.$get("/fireFightingIOT/historicalAlarmInfo/detail", {
        id: id,
      }).then(
        (res) => {
          let thisData = res.data;
          cbk && cbk(thisData);
        },
        (err) => {
          this.$message.error(err.msg || "系统错误");
        }
      );
    },
    showMonitor() {
      this.detailModalVisible = true;
    },
    handleAlarmAction(e) {
      let extData = e.target.getExtData() || e.target.getAttribution();
      this.doHandleAlarm(extData);
      // this.handleAlarmAction(extData)
      // let alarmId = extData.alarmId
      // this.activeMarkerId = 'alarm'+extData.number
      // this.getAlarmDetail(alarmId, data=>{
      // 	this.activeAlarm = data
      // 	this.handleModalVisible = true
      // 	this.getDeviceDetail(data.deviceClassify,data.number)
      // })
    },
    getDeviceMonitor(deviceId) {
      return new Promise((resolve, reject) => {
        this.$get("/fireFightingIOT/device/deviceCameraBindingList", {
          deviceId,
        }).then((res) => {
          resolve(res.data);
        });
      });
    },
    doHandleAlarm(extData, cbk) {
      this.handleModalVisibleSingle = false;
      this.activeAlarms = [];
      this.alarmDevices = [];
      let alarmId = extData.alarmId;
      this.activeMarkerId = "alarm" + extData.number;
      if (this.bgImgMarker.coordinateData) {
        this.bgImgMarker.coordinateData.forEach((item) => {
          if (item.deviceId == extData.number) {
            this.$set(item, "isWarn", true);
          }
        });
      }
      this.getAlarmDetail(alarmId, async (data) => {
        this.activeAlarms.push(data);
        // 如果是烟感设备获取该设备绑定的摄像头
        // if (data.deviceClassify == 3) {
        //     this.smokeDeviceMonitorList = await this.getDeviceMonitor(data.deviceId)
        // }
        this.getDeviceDetail(data.deviceClassify, data.number, (deviceData) => {
          this.alarmDevices.push(deviceData);
          this.$nextTick(() => {
            if (data.deviceClassify == 3) {
              // this.displaySmokeAlarm(deviceData.id, deviceData.storeyId)
              this.showHandleAlarmModal();
            } else if (deviceData.storeyId) {
              this.displayPlaneGraph(deviceData.storeyId, deviceData.id);
            } else {
              this.$set(this.handleModalVisible, data.id, true);
              // this.hasAlarmMedia = false
              this.showHandleAlarmModal();
            }
          });
        });
        cbk && cbk();
      });
    },
    // 获取平面图数据
    getPlanData(floorId, deviceId) {
      return new Promise((resolve, reject) => {
        this.$get("/business/firefightingplan/storeyDetails", {
          id: floorId,
        }).then((res) => {
          if (res.data) {
            let planeGraphDetail = res.data;
            planeGraphDetail.coordinateData =
              planeGraphDetail.coordinateData.map((item) => {
                item.isWarn = item.deviceId == deviceId;
                return item;
              });
            resolve(planeGraphDetail);
          } else {
            this.showHandleAlarmModal();
          }
        });
      });
    },
    // 展示平面图
    async displayPlaneGraph(floorId, deviceId) {
      this.planeGraphDetail = await this.getPlanData(floorId, deviceId);
      this.handleModalVisibleSingle = false;
      this.planeGraphVisible = true;
      if (alarmTimer) {
        clearTimeout(alarmTimer);
      }
      alarmTimer = setTimeout(() => {
        this.planeGraphVisible = false;
      }, 10000);
    },
    // 展示有平面图或者监控设备的烟感报警详情
    async displaySmokeAlarm(deviceId, floorId) {
      if (floorId) {
        this.planeGraphDetail = await this.getPlanData(floorId, deviceId);
      } else {
        this.planeGraphDetail = null;
      }
      this.showHandleAlarmModal();
    },
    showHandleAlarmModal() {
      this.handleModalVisibleSingle = true;
      this.planeGraphVisible = false;
    },
    submitHandleAction(item) {
      this.$refs["handle" + item.id].submitAction();
    },
    handleSuccessAction(alarmDevice) {
      if (this.bgImgMarker.coordinateData) {
        this.bgImgMarker.coordinateData.forEach((item) => {
          if (alarmDevice.number == item.deviceId) {
            this.$set(item, "isWarn", false);
          }
        });
      }
      alarmMarker["alarm" + alarmDevice.number][1].remove();
      this.removeAlarmDevice(alarmDevice);
    },
    removeAlarmDevice(alarmDevice) {
      let index = 0;
      for (let i = 0; i < this.activeAlarms.length; i++) {
        if (alarmDevice.id == this.activeAlarms[i].id) {
          index = i;
          break;
        }
      }
      this.activeAlarms.splice(index, 1);
      this.alarmDevices.splice(index, 1);
    },
    getDeviceDetail(deviceClassify, number, cbk) {
      this.$get("/fireFightingIOT/device/detail", {
        deviceClassify: deviceClassify,
        number: number,
        id: "",
      }).then(
        (res) => {
          this.alarmDevice = res.data;
          cbk && cbk(res.data);
        },
        (err) => {
          this.$message.error(err.msg || "系统错误");
        }
      );
    },
    openSocket() {
      socket = io(this.config.socketUrl, { path: "/socket.io" });
      // uid 可以为网站用户的uid，作为例子这里用session_id代替
      let uid = "1111";
      // 当socket连接后发送登录请求
      socket.on("connect", function () {
        console.log("connect");
      });
      socket.on("disconnect", function () {
        console.log("disconnect");
      });
      // 当服务端推送来消息时触发
      socket.on("new_msg", (msg) => {
        let dataArr = msg.split(",");
        let pointData = {};
        dataArr.forEach((item) => {
          let temp = item.split("=");
          pointData[temp[0]] = temp[1];
        });
        if (
          (this.deviceClassify == "0" ||
            pointData.deviceClassify == this.deviceClassify) &&
          pointData.alarmId.length > 0
        ) {
          this.$get("/fireFightingIOT/historicalAlarmInfo/isAlarm", {
            alarmId: pointData.alarmId,
          }).then(
            (res) => {
              if (res.data.flag) {
                this.showAlarmInMap(pointData);
                this.$emit("alarm");
              }
            },
            (err) => {
              //
            }
          );
        }

        // if(pointData.lng && pointData.lat){
        // 	this.$emit('alarm')
        // }
      });
      socket.open();
    },
    showAlarmInMap(pointData) {
      let lng = pointData.lon;
      let lat = pointData.lat;
      if (!lng || !lat) return;
      if (pointData.notificationType == 0) {
        if (alarmMarker["alarm" + pointData.number]) {
          map.remove(alarmMarker["alarm" + pointData.number]);
        }
        return;
      }
      if (!this.isSoundPlaying) {
        this.playSound();
      }
      // if(!!alarmMarker['alarm'+pointData.number]){
      // 	return
      // }
      if (!alarmMarker["alarm" + pointData.number]) {
        alarmMarker["alarm" + pointData.number] = [];
      }
      this.doHandleAlarm(pointData);
      if (this.mapStyle == "bigmap") {
        if (!BM) return;
        let warnIcon = BM.divIcon({
          html: '<div class="unit-warn-icon"><i class="play-pulse"></i></div>',
        });
        let bigmapMarker = BM.marker([lat, lng], {
          icon: warnIcon,
          attribution: pointData,
        }).addTo(bigmap);
        bigmapMarker.on("click", this.handleAlarmAction);
        alarmMarker["alarm" + pointData.number][0] = bigmapMarker;
      } else {
        let point = new AMap.LngLat(lng, lat);
        let marker = new AMap.Marker({ map: map, position: point });
        let markerContent = `<div class="unit-warn-icon"><i class="play-pulse"></i></div>`;
        marker.setContent(markerContent);
        marker.setExtData(pointData);
        marker.on("click", this.handleAlarmAction);
        alarmMarker["alarm" + pointData.number][1] = marker;
        let temp = Object.values(alarmMarker);
        let alarmMarkers = temp.map((item) => item[1]);
        map.setFitView(alarmMarkers);
      }
      /* let point = new AMap.LngLat(lng, lat);
			// let unitWarnIcon = new AMap.Icon({
			// 	size: new AMap.Size(30, 38),
			// 	image: require('../../assets/images/iot/unitWarn.png'),
			// 	imageSize: new AMap.Size(30, 38),
			// 	imageOffset: new AMap.Pixel(0, 0)
			// });
			// let marker = new AMap.Marker({ map: map, position: point, icon: unitWarnIcon });  // 创建标注
			// let warnIcon = require('../../assets/images/iot/unitWarn.png')
			// let markerContent = `<div class="uni-warn-icon play-drop"><img src="${warnIcon}" alt=""></div>`
			let marker = new AMap.Marker({ map: map, position: point});
			let markerContent = `<div class="unit-warn-icon"><i class="play-pulse"></i></div>`
			marker.setContent(markerContent)
			marker.setExtData(pointData)
			marker.on('click', this.handleAlarmAction);
			alarmMarker['alarm'+pointData.number] = marker
			let alarmMarkers = Object.values(alarmMarker)
			map.setFitView(alarmMarkers);

			// map.setZoomAndCenter(17, point);
			// cluster = new AMap.MarkerClusterer(map, markers, {gridSize: 80});*/
    },
    // changeFirm(value) {
    //   this.firmId = value;
    //   this.firmModalVisible = true;
    //   let selectedFirm = this.firmList.filter((item) => {
    //     return item.id == value;
    //   });
    //   this.firmTitle = selectedFirm[0].name;
    //   let lng = selectedFirm[0].lon;
    //   let lat = selectedFirm[0].lat;
    //   if (lng && lat) {
    //     let point = new AMap.LngLat(lng, lat);
    //     let marker = new AMap.Marker({ map: map, position: point });
    //     marker.setLabel({
    //       offset: new AMap.Pixel(0, 25),
    //       content: "<div class='marker-title'>" + this.firmTitle + "</div>",
    //       direction: "center",
    //     });
    //     marker.on("click", () => {
    //       this.firmModalVisible = true;
    //     });
    //     map.setZoomAndCenter(19, point);
    //   }
    // },
    openFirmDetail() {
      // this.$nextTick(()=>{
      // 	this.$refs.firmDetail.getData()
      // })
    },
    remoteMethod(query) {
      // this.loading = true;
      this.$get("/business/business/businessList", {
        name: query,
      }).then(
        (res) => {
          this.loading = false;
          this.firmList = res.data;
        },
        (err) => {
          //
        }
      );
    },
    getFirmList() {
      this.$get("/business/business/businessList").then(
        (res) => {
          this.firmList = res.data;
          // this.addFirmMarker();
          if (this.firmList.length == 0 && this.siteInfos.reginId) {
            this.getRegionDetail();
            return;
          }
          this.addCluster();
        },
        (err) => {}
      );
    },
    addFirmMarker() {
      const markers = [];
      this.firmList.forEach((item) => {
        const firmTitle = item.name;
        let lng = item.lon;
        let lat = item.lat;
        if (lng && lat) {
          let point = new AMap.LngLat(lng, lat);
          let marker = new AMap.Marker({ map: map, position: point });
          marker.setLabel({
            offset: new AMap.Pixel(0, 25),
            content: "<div class='marker-title'>" + firmTitle + "</div>",
            direction: "center",
          });
          markers.push(marker);
        }
      });
      map.setFitView(markers, false, null, 8);
    },
    // 创建地图
    createMap() {
      map = new BMap.Map("map", { enableMapClick: false });
      map.setMaxZoom(12);
      map.enableScrollWheelZoom();
      map.setMapStyleV2({ styleJson: this.config.mapStyle });
    },

    initBigMap() {
      if (!BM) return;
      bigmap = BM.map("bigmap", "bigemap.djo9kxg4", {
        crs: BM.CRS.EPSG4326,
        center: [36.05330276489258, 117.01811981201172],
        zoom: 15,
        zoomControl: false,
      });
    },
    initMap() {
      const mapOptions = {
        resizeEnable: true,
        rotateEnable: false,
        pitchEnable: false,
        expandZoomRange: true,
        zooms: [3, 20],
        zoom: 5,
        pitch: 30,
        // rotation: -15,
        buildingAnimation: false, //楼块出现是否带动画
        center: [117.01811981201172, 36.05330276489258],
        mapStyle: "amap://styles/darkblue",
      };

      if (this.siteInfos.userType == 2) {
        const { lon, lat } = this.companyInfo;
        mapOptions.center = [lon, lat];
      }
      map = new AMap.Map("map", mapOptions);
    },
    getRegionDetail(id) {
      this.$get("/business/business/regionDetail", {
        id: this.siteInfos.reginId,
      }).then(
        (res) => {
          let city = res.data.allname.split(",");
          map.setCity(city[1]);
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    renderMarker(context) {
      //自定义非聚合点样式
      let markerData = context.data[0];
      var offset = new AMap.Pixel(-8, -15);
      // context.marker.setLabel({
      //   offset: new AMap.Pixel(0, 25),
      //   content:
      //     "<div class='marker-title'>" + markerData.dataInfo.name + "</div>",
      //   direction: "center",
      // });
      context.marker.setOffset(offset);
      context.marker.setExtData(markerData);
      // 点击事件
      context.marker.on("click", () => {
        this.activeData = markerData.dataInfo;
        this.unitModalTitle = `企业单位详情(${markerData.dataInfo.name})`;
        this.unitModalVisible = true;
      });
      clusterMarkers[markerData.number] = context.marker;
    },
    getIconMarker(context) {
      let markerData = context.data[0];
      var offset = new AMap.Pixel(-8, -15);
      let img = require("../../assets/images/commandImg/icon_01.png");
      context.marker.setContent(
        `<div><img style="width:0.2rem;height:0.3rem" src="${img}" /></div>`
      );
      context.marker.setLabel({
        offset: new AMap.Pixel(0, 28),
        content:
          "<div class='marker-title amap-label'>" + markerData.name + "</div>",
        direction: "center",
      });
      context.marker.setOffset(offset);
      context.marker.setExtData(markerData);
      clusterMarkers[markerData.number] = context.marker;
    },
    renderClusterMarker(context) {
      //自定义聚合点样式
      let bgColor = "rgba(66, 157, 255, 0.8)";
      var fontColor = "#fff";
      var div = document.createElement("div");
      var borderColor = "rgba(255,255,255,.4)";
      var shadowColor = "#000";
      div.style.backgroundColor = bgColor;
      var size = context.count > 1000 ? 40 : 30;
      div.style.width = div.style.height = size + "px";
      div.style.border = "solid 1px " + borderColor;
      div.style.borderRadius = size / 2 + "px";
      div.style.boxShadow = "0 0 5px " + shadowColor;
      div.innerHTML = context.count;
      div.style.lineHeight = size + "px";
      div.style.color = fontColor;
      div.style.fontSize = "14px";
      div.style.textAlign = "center";
      context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
      context.marker.setContent(div);
      context.marker.on("click", function (e) {
        var curZoom = map.getZoom();
        if (curZoom < 20) {
          curZoom += 2;
        }
        map.setZoomAndCenter(curZoom, e.lnglat);
      });
    },
    addCluster(firmList) {
      let markers = [];
      this.clearMarkers();
      if (firmList) {
        firmList.forEach((item) => {
          const firmTitle = item.name;
          let lng = item.lon;
          let lat = item.lat;
          if (lng && lat) {
            let point = new AMap.LngLat(lng, lat);
            let marker = new AMap.Marker({ position: point });
            marker.lnglat = [point.lng, point.lat];
            marker.name = firmTitle;
            markers.push(marker);
          }
        });
        map.setFitView(); //视图自适应
      } else {
        this.firmList.forEach((item) => {
          const firmTitle = item.name;
          let lng = item.lon;
          let lat = item.lat;
          if (lng && lat) {
            let point = new AMap.LngLat(lng, lat);
            let marker = new AMap.Marker({ position: point });
            marker.lnglat = [point.lng, point.lat];
            marker.name = firmTitle;
            markers.push({
              lnglat: [item.lon, item.lat],
              dataInfo: { name: item.name, id: item.id },
            });
          }
        });
        map.setFitView(); //视图自适应
      }

      cluster = new AMap.MarkerCluster(map, markers, {
        //makers相当于参数传给renderMarker
        gridSize: 60, // 设置网格像素大小
        renderClusterMarker: this.renderClusterMarker, // 自定义聚合点样式
        renderMarker: firmList ? this.getIconMarker : this.renderMarker, // 自定义非聚合点样式
      });
    },
    clearMarkers() {
      if (cluster) {
        cluster.setMap(null);
      }
    },
    // initMap () {
    // 	map = new AMap.Map('map', {
    // 		resizeEnable: true,
    // 		rotateEnable: true,
    // 		pitchEnable: true,
    // 		expandZoomRange: true,
    // 		zoom: 15,
    // 		pitch: 30,
    // 		// rotation: -15,
    // 		// viewMode: '3D', //开启3D视图,默认为关闭
    // 		buildingAnimation: true, //楼块出现是否带动画
    // 		expandZoomRange: true,
    // 		zooms: [3, 20],
    // 		// center: [119.122356,36.713929],
    // 		mapStyle: 'amap://styles/darkblue'
    // 		// mapStyle: 'amap://styles/grey'
    // 	});
    // 	map.setCity('潍坊市')
    // },
  },
  destroyed() {
    if (this.type !== "command") {
      socket.close();
      clearInterval(clearTimer);
    }
  },
};
</script>
<style lang="less" scoped>
#map {
  position: relative;
}
</style>
